package catchData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import util.CatchDataUtil;
import util.Conts;
import util.UsualUtil;

/**
 * @author suwy
 * @date 2014-2-8
 * @todo 抓取对比过的IDS htm页面
 */
public class CatchCountryMedHtm {

	private static Logger LOG = Logger.getLogger(CatchCountryMedHtm.class);
	private static String typeName = "国产药品";
	private int tableId = 25;
	private static int[] ids = {
		
	};
	
	private void excute() {
		HttpClient client = CatchDataUtil.initHttpClient();
		PostMethod postMethod = null;
		StringBuilder stringBuilder = new StringBuilder();
		String webUrl = Conts.CWEBURL
				+ tableId
				+ "&tableName=TABLE" + tableId
				+ "&tableView=" + UsualUtil.escape(typeName)
				+ "&Id=";
		try {
			for(int i = 0; i < ids.length; i++) {
				postMethod = new PostMethod(webUrl + ids[i]);
				CatchDataUtil.setHeaders(postMethod, webUrl + ids[i],
						CatchDataUtil.getWebSite(webUrl));
				client.executeMethod(postMethod);
				stringBuilder.append(postMethod.getResponseBodyAsString());
				saveDataFile(Conts.HTM_ROOT_PATH, typeName,
						stringBuilder.toString() + "\n id is 【" + ids[i] + "】", i);
				postMethod.releaseConnection();
				stringBuilder.delete(0, stringBuilder.length());
			}
		} catch (Exception e) {
			LOG.info(e);
		} finally {
			postMethod.releaseConnection();
		}
	}
	
	protected void saveDataFile(String sFolder, String fileName, String data, int isidd) {
		File folder = new File(sFolder+"/"+fileName);
		if (!folder.exists()) folder.mkdirs();
		PrintWriter out = null;
		String saveFile = folder.toString() + "/" + isidd + ".htm";
		try {
			out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(saveFile), "gbk"));
			out.println(data);
		} catch (Exception e) {
			LOG.info(e);
		} finally {
			try {
				if (out != null) {
					out.close();
					out = null;
				}
				LOG.info(isidd + " file is finished.");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		CatchCountryMedHtm instance = new CatchCountryMedHtm();
		instance.excute();
	}

}